package top.ersredma.imagetoexcle;
         
import java.awt.Graphics;  
import java.awt.Image;  
import java.awt.image.BufferedImage;
import java.io.FileInputStream;  
import java.io.FileNotFoundException;  
import java.io.IOException;  
           
         
import javax.imageio.ImageIO;  
           
public class ImgPanel extends javax.swing.JPanel {  
            private BufferedImage image;  
            private int imgWidth;  
            private int imgHeight;  
            private int maxWidth=920;//(w/2-imgWidth/2)
            private int maxHeight=510;
            private final int xIndex=13;
            private final int YIndex=104;
            private int printW;
            private int printH;
             
            public int getImgWidth() {  
                return imgWidth;  
            }  
           
            public void setImgWidth(int imgWidth) {  
                this.imgWidth = imgWidth;  
            }  
           
            public int getImgHeight() {  
                return imgHeight;  
            }  
           
            public void setImgHeight(int imgHeight) {  
                this.imgHeight = imgHeight;  
            }  
           
            public ImgPanel (){  
                super();
            }  
           
            public void setImagePath(String imgPath) {  
                 
                // image = Toolkit.getDefaultToolkit().getImage(imgPath);  
                try {  
                     
                    image = ImageIO.read(new FileInputStream(imgPath));  
                } catch (FileNotFoundException e) {  
                    e.printStackTrace();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
                setImgWidth(image.getWidth(this));  
                setImgHeight(image.getHeight(this)); 
                System.out.println(getImgHeight()+","+getImgWidth());
            }  
            public void setImage(BufferedImage img) {  
               this.image = img;  
               setImgWidth(image.getWidth(this));  
               setImgHeight(image.getHeight(this));  
            }  
           
            @Override  
            public void paintComponent(Graphics g1) {  
                double d=maxWidth/(double)imgWidth>maxHeight/(double)imgHeight?maxHeight/(double)imgHeight:maxWidth/(double)imgWidth;
                printW=(int)(d*imgWidth);
                printH=(int)(d*imgHeight);
                int x = (maxWidth-printW)/2+xIndex;  
                int y = (maxHeight-printH)/2+YIndex;  
                Graphics g = (Graphics) g1;  
                if (null == image) {  
                    return;  
                }  
                g.drawImage(image, x, y, printW, printH,  
                        this);  
                g = null;  
            }  
            public BufferedImage getImage(){
                return this.image;
            }
        }